package com.distributed.logicserver;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.distributed.common.DefaultEventHandler;
import com.distributed.common.EventHandler;

public class LogicProtocolHandler extends IoHandlerAdapter {
	private final static Logger logger = Logger.getLogger(LogicProtocolHandler.class);
	
	private static EventHandler eventHandler = new DefaultEventHandler();
	
	public void setHandler(EventHandler handler) {
		eventHandler = handler;
	}
	
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("session created");
		session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		super.sessionCreated(session);
	}
	
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("session opened");
		super.sessionOpened(session);
	}
	
	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		logger.info("session idle: " + session.getIdleCount(IdleStatus.BOTH_IDLE));
		super.sessionIdle(session, status);
	}
	
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("session close");
		eventHandler.closeSession(session);
		super.sessionClosed(session);
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.warn("exception caught: " + cause.getMessage());
		session.close(true);
	}
	
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		logger.info("message received: " + message);
		String respMessage = eventHandler.process(session, (String)message);
		if (respMessage != null) { 
			session.write(respMessage);
		}
	}
}
